import concurrent
from concurrent.futures import ThreadPoolExecutor
from datetime import datetime, timedelta

from third_services.aliexpress.api.api import AliexpressApi
from utils.mysqlUtils.mongodb_utils import MongoDBLink


class ChoiceListingList:
    def __init__(self,source_id):
        self.source_id = source_id
        '''
        1. 22311 - Aliexpress-Z00003-全托管 - "channel_seller_id": 2679840215
        '''
        self.api = AliexpressApi(self.source_id)

    def get_choice_product_list(self, index,):
        choice_product_data = self.api.get_choice_product_list(index,).get("result").get("product_list").get("product")
        choice_product_items = list(set(map(lambda x:x.get("product_id"),choice_product_data)))
        return choice_product_items

    def choice_product_list(self,):
        # 获取总页数（假设每页500条记录）
        page_size = self.api.get_choice_product_list(1).get("result").get("total_page")

        # 使用ThreadPoolExecutor并行获取数据
        with ThreadPoolExecutor(max_workers=6) as executor:
            future_to_index = {executor.submit(self.get_choice_product_list, index): index for index in
                               range(1, page_size + 1)}
            choice_product_list = []
            exception_list = []
            for future in concurrent.futures.as_completed(future_to_index):
                try:
                    product_list = future.result()
                    if product_list:
                        choice_product_list.append(product_list)
                except Exception as exc:
                    exception_list.append(self.get_choice_product_list(future_to_index[future],))
                    print(f'Error fetching data for page {future_to_index[future]}: {exc}')
        choice_product_list.append(exception_list)
        choice_product_result = [item for sublist in choice_product_list for item in sublist]
        print(len(choice_product_result),len(exception_list))
        return choice_product_result

    def check_listing(self,status:str):
        test_listing_pull_list_original_aliexpress = MongoDBLink(
            uri='mongodb://admin:Zhcx?2021@10.158.158.29:27017/?authSource=admin',
            dbname='test_zhcxkj_java_center', coll_name='t_listing_pull_list_original_aliexpress')

        filter_object = {
            "$and": [{"listingType": 2},
                     {"sourceId": 20463},
                     {"listingStatus": status}]
        }
        projection_1 = {"_id": 0,"productId": 1}  # 如果您只想排除_id字段
        mongo_result = test_listing_pull_list_original_aliexpress.select(filter_object, projection_1)

        mongo_result_items = set(map(lambda x: x.get("productId"), mongo_result))
        choice_product_list = set(self.choice_product_list())
        different_mongo_set = mongo_result_items - choice_product_list
        different_interface_set = choice_product_list - mongo_result_items

        if different_mongo_set is None and different_interface_set is None:
            return True
        else:
            print(f'{self.source_id}:进入mongo的listing有{len(mongo_result_items)}个,{self.source_id}:程序通过接口获取的listing有{len(choice_product_list)}个,'
                  f'{self.source_id}:mongo多余的数据有:{different_mongo_set},{different_mongo_set}:接口多余的数据有:{different_interface_set}')
            print(f'-----------------------------------------')


if __name__ == '__main__':
    # ChoiceListingList().get_choice_product_list(1)
    # print(ChoiceListingList(22311).choice_product_list())
    ChoiceListingList(20463).check_listing()


    # 25分